package yxy.game.pm2.chat.command.friends;

import java.util.Collection;

import yxy.cherry.game.base.message.MessageEmitterHandler;
import yxy.cherry.game.base.message.annotation.MessageSource;
import yxy.cherry.game.base.message.annotation.MessageType;
import yxy.game.pm2.Result;
import yxy.game.pm2.bean.Nickname;
import yxy.game.pm2.bean.PlayerBean;
import yxy.game.pm2.bean.ServerBean;
import yxy.game.pm2.bean.area.AreaBean;
import yxy.game.pm2.command.Command;
import yxy.game.pm2.message.FriendMessage;
import yxy.game.pm2.module.player.PlayerHandle;

/** 好友 搜索玩家 */
@MessageType(proto = Command.FriendSearch, classtype = FriendMessage.FriendSearchRequest.class)
public class CMD_FriendSearch extends Command<FriendMessage.FriendSearchRequest> {

	@Override
	public void execute(MessageSource messageSource, FriendMessage.FriendSearchRequest request) {
		String playerCode = messageSource.getTag();
		String keyword = request.getKeyword();

		FriendMessage.FriendSearchResponse.Builder response = FriendMessage.FriendSearchResponse.newBuilder();

		PlayerBean playerBean = PlayerBean.get(playerCode);
		ServerBean serverBean = ServerBean.get(playerBean.getServerId());
		AreaBean areaBean = AreaBean.get(serverBean.getAreaId());
		Collection<String> search = Nickname.search(areaBean.getClusterId(), areaBean.getGroupId(), keyword, 20);// 只搜索20个结果
		for (String code : search) {
			if (code.equals(playerCode)) {
				continue;
			}
			response.addPlayers(new PlayerHandle().playerSimpleInfo(code));
		}

		send(messageSource, response, Result.Success);
	}

	private void send(MessageSource messageSource, FriendMessage.FriendSearchResponse.Builder response, Result result) {
		response.setResult(result.packResult());
		MessageEmitterHandler.getInstance().send(messageSource, response.build());
	}
}